using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Phoenix.Xna.Framework.Graphics.Animation;
using Phoenix.Xna.Framework.Graphics.Models;
using Phoenix.Xna.Framework.Reflection;

namespace Phoenix.Xna.Framework.ContentPipeline.Models
{
    public class SkinnedModelReader : ContentTypeReader<SkinnedModel>
    {
        protected override SkinnedModel Read(ContentReader input, SkinnedModel existingInstance)
        {
            SkinnedModel model = ReflectionHelper.CreateInstance<SkinnedModel>();
            ReflectionHelper.SetProperty<SkinnedModel>(model, "Model", input.ReadObject<Model>());

            int boneCount = input.ReadInt32();
            List<SkinnedModelBone> bones = new List<SkinnedModelBone>(boneCount);

            for (int i = 0; i < boneCount; i++)
            {
                input.ReadSharedResource<SkinnedModelBone>(delegate(SkinnedModelBone skinnedBone)
                {
                    bones.Add(skinnedBone);
                });
            }

            ReflectionHelper.SetProperty<SkinnedModel>(model, "SkeletonBones", new SkinnedModelBoneCollection(bones));
            int clipCount = input.ReadInt32();
            Dictionary<string, AnimationClip> clips = new Dictionary<string, AnimationClip>();

            for (int i = 0; i < clipCount; i++)
            {
                input.ReadSharedResource<AnimationClip>(delegate(AnimationClip animationClip)
                {
                    clips.Add(animationClip.Name, animationClip);
                });
            }

            ReflectionHelper.SetProperty<SkinnedModel>(model, "AnimationClips", new AnimationClipDictionary(clips));
            return model;
        }
    }
}